package com.hr.rbac.servlet;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.map.HashedMap;

import com.hr.rbac.domain.Function;
import com.hr.rbac.domain.Privilege;
import com.hr.rbac.domain.Role;
import com.hr.rbac.service.RBACService;
import com.hr.rbac.service.Impl.FunctionServiceImpl;
import com.hr.rbac.service.Impl.PrivilegeServiceImpl;
import com.hr.rbac.service.Impl.RoleServiceImpl;
import com.hr.user.domain.User;
import com.hr.user.service.Impl.UserServiceImpl;
import com.hr.utils.BaseServlet;
import com.hr.utils.CommonUtils;
import com.hr.utils.PageBean;

/**
 * @author 杨谦
 * @date 2015-11-5
 *
 */
public class RoleServlet extends BaseServlet {
	
	private RoleServiceImpl roleServiceImpl = new RoleServiceImpl();
	private PrivilegeServiceImpl privilegeServiceImpl = new PrivilegeServiceImpl();
	private FunctionServiceImpl functionServiceImpl = new FunctionServiceImpl();
	private UserServiceImpl userServiceImpl = new UserServiceImpl();
	private RBACService rbacService = new RBACService();
	
	/**
	 * 查询所有角色
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String queryAllRole (HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		/**
		 * 1、获取页面传递的PageCurrent
		 * 2、给定PageSize的值
		 * 3、使用PageCurrent和PageSize调用Service方法，得到PageBean，保存request域
		 * 4、转发到/admin/dept_info.jsp
		 */
		int PageCurrent = getPageCurrent(request);//获取当前页
		int PageSize = 3;//获取每页的记录数
		PageBean<Role> pageBean = roleServiceImpl.queryAll_Page(PageCurrent, PageSize);
		pageBean.setUrl(getUrl(request));
		request.setAttribute("pb", pageBean);
		return "f:/admin/role_info.jsp";
	}
	/**
	 * 获取当前的页面值
	 * @param request
	 * @return
	 */
	private int getPageCurrent(HttpServletRequest request){
		String value = request.getParameter("PageCurrent");
		if(value == null || value.trim().isEmpty()){
			return 1;
		} else{
			return Integer.parseInt(value);
		}
	}
	
	/**
	 * 截取url
	 * @param request
	 * @return
	 */
	public String getUrl(HttpServletRequest request){
		String contextPath = request.getContextPath();//获取项目名
		String servletPath = request.getServletPath();//获取servletPath，即/CustomerServlet
		String queryString = request.getQueryString();//获取问号之后的参数部份
		
		//  判断参数部份中是否包含pc这个参数，如果包含，需要截取下去，不要这一部份。
		if(queryString.contains("&PageCurrent=")) {
			int index = queryString.lastIndexOf("&PageCurrent=");
			queryString = queryString.substring(0, index);
		}
		
		return contextPath + servletPath + "?" + queryString;
	}
	
	/**
	 * 添加角色准备
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String addRolePre (HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		List<Privilege> privileges = privilegeServiceImpl.queryAllPrivilege();
		for(int i=0;i<privileges.size();i++) {
			privileges.get(i).setFunctions(functionServiceImpl.findAllfunctionsByPrivilegeID(privileges.get(i).getPrivilege_id()));
		}
		request.setAttribute("privileges", privileges);
		return "f:/admin/role_add.jsp";
	}
	
	/**
	 * 添加角色
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String addRole (HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		
		Role role = new Role();
		String rolename = request.getParameter("rolename");
		role.setRole_ID(CommonUtils.uuid());
		role.setRole_Name(rolename);
		roleServiceImpl.save(role);
		
		String[] privileges = request.getParameterValues("privileges");
		String[] functions = request.getParameterValues("functions");
		
		if(privileges!=null && privileges.length>0){
			for(int j = 0;j < privileges.length;j++){
				roleServiceImpl.saveRole_Privilege(privileges[j], role.getRole_ID());
			}
		}
		
		if(functions!=null && functions.length>0){
			for(int i = 0;i < functions.length;i++) {
				String[] f = functions[i].split(",");
				roleServiceImpl.saveRole(f[1],f[0],role.getRole_ID());
			}
		}
		
		request.setAttribute("msg", "添加角色成功");
		request.setAttribute("PageCurrent", 0);
		
		return "f:/RoleServlet?method=queryAllRole";
	}
	
	/**
	 * 修改角色准备
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String updateRolePre(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException{
		String role_ID = request.getParameter("role_ID");
		Role role_find = roleServiceImpl.findRoleByRoleID(role_ID);
		List<Privilege> privileges_find = privilegeServiceImpl.findByRoleId(role_ID);
		
		for(int i=0;i<privileges_find.size();i++) {
			privileges_find.get(i).setFunctions(functionServiceImpl.findByPrivilegeID(privileges_find.get(i)));
		}
		
		List<Privilege> privileges = privilegeServiceImpl.queryAllPrivilege();
		for(int i=0;i<privileges.size();i++) {
			privileges.get(i).setFunctions(functionServiceImpl.findAllfunctionsByPrivilegeID(privileges.get(i).getPrivilege_id()));
		}
		
		request.setAttribute("role_find", role_find);
		request.setAttribute("privileges_find", privileges_find);
		request.setAttribute("privileges", privileges);
		
		return "f:/admin/role_edit.jsp";
	}
	
	/**
	 * 修改角色信息
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String updateRole(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException{
		String role_id = request.getParameter("role_id");
		String role_name = request.getParameter("role_name");
		
		Role role = new Role(); 
		role.setRole_ID(role_id);
		role.setRole_Name(role_name);
		
		roleServiceImpl.deleteRoleByRoleID(role_id);
		
		roleServiceImpl.save(role);
		
		String[] privileges = request.getParameterValues("privileges");
		String[] functions = request.getParameterValues("functions");
		
		if(privileges!=null && privileges.length>0){
			for(int j = 0;j < privileges.length;j++){
				roleServiceImpl.saveRole_Privilege(privileges[j], role.getRole_ID());
			}
		}
		
		if(functions!=null && functions.length>0){
			for(int i = 0;i < functions.length;i++) {
				String[] f = functions[i].split(",");
				roleServiceImpl.saveRole(f[1],f[0],role.getRole_ID());
			}
		}
		
		request.setAttribute("msg", "修改角色成功");
		request.setAttribute("PageCurrent", 0);
		
		return "f:/RoleServlet?method=queryAllRole";
	}
	
	public String deleteRole(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException{
		
		String role_id = request.getParameter("role_ID");
		roleServiceImpl.deleteRoleByRoleID(role_id);
		
		return "f:/RoleServlet?method=queryAllRole";
	}
	
	/**
	 * 查询系统中所有的员工角色
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String empRoleInfo(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException{
		int PageCurrent = getPageCurrent(request);//获取当前页
		int PageSize = 5;//获取每页的记录数
		PageBean<User> pageBean = userServiceImpl.queryAll_Page(PageCurrent, PageSize);
		pageBean.setUrl(getUrl(request));
		
		Map<String, String> map_user_role = new HashedMap();
		
		List<User> user_list = pageBean.getBeanList();
		
		for(User user : user_list) {
			if(rbacService.findByUserID(user.getUser_id()) != null) {
				map_user_role.put(user.getUser_id(), rbacService.findByUserID(user.getUser_id()).getRole_Name());
			} else {
				map_user_role.put(null, "<font color = 'red'>还没有进行权限分配</font>");
			}
		}
		
		request.setAttribute("pb", pageBean);
		request.setAttribute("map_user_role", map_user_role);
		return "f:/admin/emp_role_info.jsp";
	}
	
	/**
	 * 给员工分配角色
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String empRolePre(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		List<Role> roles = roleServiceImpl.queryAllRole();
		List<User> users = userServiceImpl.queryAllUser();
		
		request.setAttribute("roles", roles);
		request.setAttribute("users", users);
		
		return "f:/admin/emp_role_add.jsp";
	}
	
	/**
	 * 修改员工角色前的准备
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String UpdateRoleUserPre(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		
		List<Role> roles = roleServiceImpl.queryAllRole();
		List<User> users = userServiceImpl.queryAllUser();
		
		request.setAttribute("roles", roles);
		request.setAttribute("users", users);
		
		String user_id = request.getParameter("user_id");
		User user_find = userServiceImpl.findByUserID(user_id);
		Role role_find = rbacService.findByUserID(user_id);
		
		request.setAttribute("user_find", user_find);
		request.setAttribute("role_find", role_find);
		
		return "f:/admin/emp_role_edit.jsp";
	}
	
	/**
	 * 给员工添加角色
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String addRoleUser(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		
		String user_id = request.getParameter("user_id");
		String role_id = request.getParameter("role_id");
		roleServiceImpl.saveRoleAndUser(user_id,role_id);
		
		return "f:/RoleServlet?method=empRoleInfo";
	}
	
	/**
	 * 修改员工角色信息
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String updateRoleUser(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		String user_id = request.getParameter("user_id");
		String role_id = request.getParameter("role_id");
		roleServiceImpl.updateRoleAndUser(user_id,role_id);
		return "f:/RoleServlet?method=empRoleInfo";
	}
	
}